<?php

namespace app\api\controller;

use app\api\model\Task;
use app\common\controller\Api;
use app\common\library\Image;
use think\Db;
use Exception;
use fast\Random;
use think\exception\PDOException;

/**
 * 阅卷任务
 */
class Make extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $blockType = ['alone' => '单评', 'dual' => '双评'];
    protected $allotType = ['1' => '平均分配', '2' => '效率优先', 3 => '定量分配'];
    protected $statusType = ['0' => '待阅', '1' => '阅卷中', '2' => '已完成', 3 => '暂停中'];

    //分配阅卷任务列表
    public function examTask()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $teacherId = $this->request->post('teacherId');
        $month = $this->request->post('month');
        $status = $this->request->post('status', -1);
        $name = $this->request->post('name');
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        if (!$teacherId) $this->error('未知参数！');
        $blockList = db('exam_paper_block')
            ->alias('b')
            ->join('exam_list l', 'b.exams_list_id=l.id')
            ->join('exams e', 'b.exams_id=e.id')
            ->where("FIND_IN_SET(" . $teacherId . ",b.teacher_ids)")
            ->where('l.status',2)
            ->where(function ($query) use ($status) {
                if (in_array($status, [1, 2, 3])) {
                    $query->where(['b.status' => $status]);
                }
            })
            ->where(function ($query) use ($month) {
                if ($month) {
                    $query->where('FROM_UNIXTIME(starttime,"%Y-%m")="' . $month . '"');
                }
            })
            ->where(function ($query) use ($name) {
                if ($name) {
                    $query->where('l.name|e.name', 'like', '%' . $name . '%');
                }
            })
            ->field('b.id,b.exams_list_id,b.exams_id,b.status,l.name as lname,e.name as ename, e.starttime,e.endtime')
            ->group('b.exams_list_id')
            ->paginate($pagesize, false)->each(function ($item, $index) {

                $item['starttime_text'] = date('Y-m-d H:i:s', $item['starttime']);
                $item['endtime_text'] = date('Y-m-d H:i:s', $item['endtime']);
                $item['status_text'] = $this->statusType[$item['status']];
                return $item;
            });

        $this->success('阅卷任务列表', $blockList);
    }

    //题块列表
    public function taskDetail()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $teacherId = $this->request->post('teacherId');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$teacherId || !$exams_list_id) $this->error('未知参数！');
        $list = db('exam_paper_block')->where(['exams_list_id' => $exams_list_id])->where("FIND_IN_SET(" . $teacherId . ",teacher_ids)")->field('id,exams_id,exams_list_id,name,score,params,type,staynum,alreadynum,firstnum,finalnum,status,content')->select();

        foreach ($list as &$value) {
            $value['type_text'] = $this->blockType[$value['type']];
            $value['params_text'] = json_decode($value['params'], true);
            $value['content_text'] = json_decode($value['content'], true);
            $question = [];
            if (is_array($value['params_text']) && !empty($value['params_text'])) {
                foreach ($value['params_text'] as $param) {
                    foreach ($param['son'] as $son) {
                        $question[] = $son['name'];
                    }
                }
            }
            $value['question'] = implode(',', $question);
            //学生数量
            $value['studendnum'] = db('exam_list')->where('id', $exams_list_id)->value('studentnum');
            //已上传数量
            $value['uppapernum'] = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'page' => 1])->count();

            //单评我已阅数量
            $value['mymakenum'] = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'teacher_id' => $teacherId, 'block_id' => $value['id']])->where('type', 'in', [1, 4])->count();
            //初评我已阅数量
            $value['myfirstmakenum'] = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'teacher_id' => $teacherId, 'block_id' => $value['id'], 'type' => 2])->count();
            //终评我已阅数量
            $value['myfinalmakenum'] = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'teacher_id' => $teacherId, 'block_id' => $value['id'], 'type' => 3])->count();
            
            //总剩余数量（待阅数量）=已上传数量-已阅数量
            $value['surplusnum'] = intval(bcsub($value['uppapernum'], $value['alreadynum'], 0));

            if ($value['uppapernum'] > 0) {
                //单评进度
                $value['alonejindu'] = round(($value['mymakenum'] / $value['uppapernum']) * 100, 2);
                //初评进度
                $value['firstjindu'] = round(($value['myfirstmakenum'] / $value['uppapernum']) * 100, 2);
                //终评进度
                $value['finaljindu'] = round(($value['myfinalmakenum'] / $value['uppapernum']) * 100, 2);
            } else {
                $value['alonejindu'] = 0;
                $value['firstjindu'] = 0;
                $value['finaljindu'] = 0;
            }
            $value['status_text'] = $this->statusType[$value['status']];

            //阅卷记录
            $makeLog = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'teacher_id' => $teacherId, 'block_id' => $value['id']])->find();
            $isping = 0;
            if ($makeLog) {
                $isping = 1;
            }
            $value['isping'] = $isping;
        }

        $this->success('题块列表', $list);
    }

    //学生答题卡列表
    public function studentPaperList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id) $this->error('未知参数！');
        $group = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'status' => 3])->field('key')->group('key')->select(); //, 'ispart' => 0
        $data = [];
        foreach ($group as $key => &$value) {
            $list = db('exam_paper_images')->where(['key' => $value['key']])->field('id,exams_list_id,key,image,page')->order('page desc')->select();
            $data[$key]['list'] = $list;
        }
        $this->success('学生答题卡列表', $data);
    }

    //保存学生主观题分隔图片
    public function setZhuImage()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $zhudivide = $this->request->param('zhudivide/a');
        if (!is_array($zhudivide)) $this->error('参数错误！');
        $paper = db('exam_paper_images')->where(['id' => $id])->find();
        if (!$paper) $this->error('未找到相关信息！');
        $up = db('exam_paper_images')->where(['id' => $id])->update([
            'zhudivide' => json_encode($zhudivide),
            'ispart' => 1
        ]);
        if (!$up) $this->error('操作失败');
        $this->success('操作成功！');
    }

    //批量保存学生主观题分隔图片
    public function setBatchZhuImage()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $params = $this->request->param('params/a');
        if (!is_array($params)) $this->error('参数错误！');
        foreach ($params as $key => $value) {
            $zhudivide = $value['zhudivide']; //, 'ispart' => 0
            $paper = db('exam_paper_images')->where(['id' => $value['id'], 'ispart' => 0])->find();
            if (!$paper) continue;
            foreach ($zhudivide as &$val) {
                $imageArray = explode(',', $val['image']);
                $imageList = [];
                $mairk = '';
                foreach ($imageArray as $image) {
                    $fileimage = pathinfo($image);
                    $imagePath = explode('.com', $fileimage['dirname']);
                    $imageList[] = $imagePath[1] . '/' . $fileimage['basename'];
                    $mairk = $imagePath[1];
                }
                $outputFile =  $mairk . '/' . md5(date('YmdHis', time()) . Random::uuid()) . '.png';
                Image::generate($outputFile, "png", 1, $imageList);
                $val['mergeImage'] = cdnurl($outputFile, true);
            }
            $up = db('exam_paper_images')->where(['id' => $value['id']])->update([
                'zhudivide' => json_encode($zhudivide),
                'ispart' => 1
            ]);
            if (!$up) continue;
        }

        $this->success('操作成功！');
    }


    //试卷题块列表
    public function paperBlockList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $block_id = $this->request->post('block_id');
        $teacher_id = $this->request->post('teacher_id');
        if (!$exams_list_id || !$block_id) $this->error('未知参数！');
        $blockinfo = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$blockinfo) $this->error('未找到相关题块信息！');
        $list = db('exam_paper_images')
            ->where(['exams_list_id' => $exams_list_id, 'status' => 3])
            ->select();
        $data = [];
        foreach ($list as $key => $value) {
            if ($value['zhudivide']) {
                $zhudivide = json_decode($value['zhudivide'], true);
                foreach ($zhudivide as $block) {
                    if ($block['block_id'] == $block_id) {
                        //阅卷记录
                        $makeLog = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id, 'student_id' => $value['student_id']])->order('createtime desc')->find();
                        $distinguish = [];
                        $paintList = [];
                        $saveblocktime = '';
                        $appraiseLevel = 0;
                        if ($makeLog) {
                            $distinguish = json_decode($makeLog['distinguish'], true);
                            $paintList = json_decode($makeLog['paintList'], true);
                            $saveblocktime = date('Y-m-d H:i:s', $makeLog['createtime']);
                            $appraiseLevel = $makeLog['appraiseLevel'];
                        }
                        $data1 = [
                            'id' => $value['id'],
                            'block_id' => $block['block_id'],
                            'student_id' => $value['student_id'],
                            'image' => $block['mergeImage'],
                            'params' => json_decode($blockinfo['params'], true),
                            'zhudivide' => json_decode($value['zhudivide'], true),
                            'distinguish' => $distinguish,
                            'paintList' => $paintList,
                            'saveblocktime' => $saveblocktime,
                            'appraiseLevel' => $appraiseLevel
                        ];
                        array_push($data, $data1);
                    }
                }
            }
        }
        $this->success('试卷题块列表', $data);
    }

    //老师阅卷历史
    public function teacherTaskLog()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $block_id = $this->request->post('block_id');
        $teacherId = $this->request->post('teacherId');
        $type = $this->request->post('type');
        if (!$exams_list_id || !$teacherId || !$block_id || !in_array($type, [1, 2, 3])) $this->error('未知参数！');
        $list = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'teacher_id' => $teacherId, 'block_id' => $block_id])->where(function($query) use($type){
            if (in_array($type,[2,3])) {
               $query->where('type',$type);
            }
        })->order('createtime asc')->select();
        foreach ($list as &$value) {
            $value['distinguish'] = json_decode($value['distinguish'], true);
            $value['paintList'] = json_decode($value['paintList'], true);
            $paperList = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $value['student_id']])->select();
            $data = [];
            foreach ($paperList as $paper) {
                if ($paper['zhudivide'] != null) {
                    $zhudivide = json_decode($paper['zhudivide'], true);
                    foreach ($zhudivide as $block) {
                        if ($block['block_id'] == $block_id) {
                            $data[] = $block;
                        }
                    }
                    
                }
            }
            $blockinfo = db('exam_paper_block')->where(['id' => $block_id])->find();
            $value['params'] = json_decode($blockinfo['params'], true);
            $value['zhudivide'] = $data;
        }
        $this->success('老师阅卷历史', $list);
    }

    //判卷信息
    public function makeExam()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $block_id = $this->request->post('block_id');
        $teacher_id = $this->request->post('teacher_id');
        $appraiseLevel = $this->request->post('appraiseLevel');
        $blockscore = $this->request->post('total');
        $type = $this->request->post('type');
        if (!$id || !$block_id || !$teacher_id || !in_array($type, [1, 2, 3, 4, 5])) $this->error('未知参数！');
        $distinguish = $this->request->param('distinguish/a');
        $paintList = $this->request->param('paintList/a');
        if (!is_array($distinguish) || !is_array($paintList)) $this->error('参数错误！');
        $blockinfo = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$blockinfo) $this->error('未找到相关题块信息！');
        $paperImage = db('exam_paper_images')->where(['student_id' => $id, 'exams_list_id' => $blockinfo['exams_list_id'], 'page' => 1])->find();
        if (!$paperImage) $this->error('未找到相关试卷信息!');
        $result = false;
        Db::startTrans();
        try {
            if ($type == 4) {
                db('exam_teacher_make_log')->where(['exams_list_id' => $paperImage['exams_list_id'], 'student_id' => $paperImage['student_id'], 'block_id' => $block_id,'teacher_id'=>$teacher_id])->where(function($query) use($type){
                    if (!$type == 4) {
                        $query->where('type',$type);
                    }
                })->delete();
                $in = db('exam_teacher_make_log')->insertGetId([
                    'exams_id' => $paperImage['exams_id'],
                    'exams_list_id' => $paperImage['exams_list_id'],
                    'teacher_id' => $teacher_id,
                    'student_id' => $paperImage['student_id'],
                    'student_name' => $paperImage['student_name'],
                    'exam_number' => $paperImage['exam_number'],
                    'stu_number' => $paperImage['stu_number'],
                    'block_id' => $block_id,
                    'class_id' => $paperImage['class_id'],
                    'bscore' => $blockscore,
                    'appraiseLevel' => $appraiseLevel,
                    'distinguish' => json_encode($distinguish),
                    'paintList' => json_encode($paintList),
                    'type' => $type,
                    'createtime' => time()
                ]);
                if ($in) $result = true;
            } else {
                db('exam_teacher_make_log')->where(['exams_list_id' => $paperImage['exams_list_id'], 'student_id' => $paperImage['student_id'], 'block_id' => $block_id,'teacher_id'=>$teacher_id])->where(function($query) use($type){
                    if (in_array($type,[1,2,3])) {
                        $query->where('type',$type);
                    }
                })->delete();
                
                db('exam_paper_images')->where(['id' => $paperImage['id']])->setInc('zscoresum', $blockscore);
                $in = db('exam_teacher_make_log')->insertGetId([
                    'exams_id' => $paperImage['exams_id'],
                    'exams_list_id' => $paperImage['exams_list_id'],
                    'teacher_id' => $teacher_id,
                    'student_id' => $paperImage['student_id'],
                    'student_name' => $paperImage['student_name'],
                    'exam_number' => $paperImage['exam_number'],
                    'stu_number' => $paperImage['stu_number'],
                    'block_id' => $block_id,
                    'class_id' => $paperImage['class_id'],
                    'bscore' => $blockscore,
                    'appraiseLevel' => $appraiseLevel,
                    'distinguish' => json_encode($distinguish),
                    'paintList' => json_encode($paintList),
                    'type' => $type,
                    'createtime' => time()
                ]);
                if ($in) $result = true;
                if ($type == 1 || $type == 3) {
                    db('exam_paper_block')->where(['id' => $block_id])->setInc('alreadynum', 1);
                }
            }
            if ($type == 1 || $type == 2 || $type == 3) {
                db('task')->where(['exams_list_id' => $paperImage['exams_list_id'], 'block_id' => $block_id, 'student_id' => $paperImage['student_id'],'num'=>$type])->update(['status' => 2]);
            }

            //判断题块阅卷是否完成
            // $alreadynum = db('exam_paper_block')->where(['id' => $block_id])->value('alreadynum');
            $alreadynum = db('exam_paper_images')->where(['exams_list_id' => $paperImage['exams_list_id'],'page'=>1])->count();
            $studentnum = db('exam_list')->where(['id' => $paperImage['exams_list_id']])->value('studentnum');
            if ($alreadynum == $studentnum) {
                db('exam_paper_block')->where(['id' => $block_id])->update(['status' => 2]);
            }
            //判断科目阅卷是否完成
            //科目题块数量
            $blocknum = db('exam_paper_block')->where(['exams_list_id' => $paperImage['exams_list_id']])->count();
            //阅卷已完成的题块数
            $taskBlocknum = db('exam_paper_block')->where(['exams_list_id' => $paperImage['exams_list_id'], 'status' => 2])->count();
            if ($blocknum == $taskBlocknum) {
                db('exam_list')->where(['id' => $paperImage['exams_list_id']])->update(['status' => 3]);
            }
            //判断考试是否阅卷完成
            //科目总数
            $examListNum = db('exam_list')->where(['exams_id' => $paperImage['exams_id']])->count();
            //待统分科目总数
            $overTaskNum = db('exam_list')->where(['exams_id' => $paperImage['exams_id'], 'status' => 3])->count();
            if ($examListNum == $overTaskNum) {
                db('exams')->where(['id' => $paperImage['exams_id']])->update(['status' => 3]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加成功！');
        } else {
            $this->error('添加失败！');
        }
    }

    //试卷题块列表
    public function paperBlockListNew()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $block_id = $this->request->post('block_id');
        $teacher_id = $this->request->post('teacher_id');
        $type = $this->request->post('type');
        if (!$exams_list_id || !$block_id || !in_array($type, [1, 2, 3])) $this->error('未知参数！');
        $blockinfo = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$blockinfo) $this->error('未找到相关题块信息！');
        //获取任务
        $task = Task::getTasks($type, $exams_list_id, $block_id, $teacher_id);
        if (!$task) $this->error('已完成阅卷任务');
        //学生总数
        $studentNum = db('task')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id])->group('student_id')->count();
        //该老师已阅数
        $tMakeNum = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id, 'teacher_id' => $teacher_id])->where(function($query) use($type){
            if (in_array($type,[2,3])) {
               $query->where('type',$type);
            }
        })->count();
        //阅卷老师数量
        $teacherArr = explode(',', $blockinfo['teacher_ids']);
        $teacherNum = count($teacherArr);

        //阅卷类型
        switch ($blockinfo['allot_type']) {
            case '1':
                #平均分配
                $makeNum = round($studentNum / $teacherNum);
                break;
            case '2':
                #效率优先
                $makeNum = 0;
                break;
            case '3':
                #定量分配
                $makeNum = round($studentNum / $teacherNum);
                break;
        }

        
        $paperList = db('exam_paper_images')
            ->where(['exams_list_id' => $exams_list_id, 'student_id' => $task['student_id']])
            ->select();
            	
        
        if (empty($paperList)) $this->success('试卷题块列表', []);
        $data = [];
        if ($makeNum <= 0) {
            
            foreach ($paperList as $paper) {
                if ($paper['zhudivide']) {
                    $zhudivide = json_decode($paper['zhudivide'], true);
                    
                    foreach ($zhudivide as $block) {
                        if ($block['block_id'] == $block_id) {
                            //阅卷记录
                            $makeLog = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id, 'student_id' => $paper['student_id'], 'type' => $type])->order('createtime desc')->find();
                            $distinguish = [];
                            $paintList = [];
                            $saveblocktime = '';
                            $appraiseLevel = 0;
                            if ($makeLog) {
                                $distinguish = json_decode($makeLog['distinguish'], true);
                                $paintList = json_decode($makeLog['paintList'], true);
                                $saveblocktime = date('Y-m-d H:i:s', $makeLog['createtime']);
                                $appraiseLevel = $makeLog['appraiseLevel'];
                            }
                            $data[] = [
                                'id' => $paper['id'],
                                'block_id' => $block['block_id'],
                                'student_id' => $paper['student_id'],
                                'image' => $block['mergeImage'],
                                'params' => json_decode($blockinfo['params'], true),
                                'zhudivide' => $block,
                                'distinguish' => $distinguish,
                                'paintList' => $paintList,
                                'saveblocktime' => $saveblocktime,
                                'appraiseLevel' => $appraiseLevel
                            ];
                        }
                    }
                    
                }
            }
        } else {
            if ($tMakeNum < $makeNum) {
                foreach ($paperList as $paper) {
                    if ($paper['zhudivide']) {
                        $zhudivide = json_decode($paper['zhudivide'], true);
                        foreach ($zhudivide as $block) {
                            if ($block['block_id'] == $block_id) {
                                //阅卷记录
                                $makeLog = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id, 'student_id' => $paper['student_id'], 'type' => $type])->order('createtime desc')->find();
                                $distinguish = [];
                                $paintList = [];
                                $saveblocktime = '';
                                $appraiseLevel = 0;
                                if ($makeLog) {
                                    $distinguish = json_decode($makeLog['distinguish'], true);
                                    $paintList = json_decode($makeLog['paintList'], true);
                                    $saveblocktime = date('Y-m-d H:i:s', $makeLog['createtime']);
                                    $appraiseLevel = $makeLog['appraiseLevel'];
                                }
                                $data[] = [
                                    'id' => $paper['id'],
                                    'block_id' => $block['block_id'],
                                    'student_id' => $paper['student_id'],
                                    'image' => $block['mergeImage'],
                                    'params' => json_decode($blockinfo['params'], true),
                                    'zhudivide' => $block,
                                    'distinguish' => $distinguish,
                                    'paintList' => $paintList,
                                    'saveblocktime' => $saveblocktime,
                                    'appraiseLevel' => $appraiseLevel
                                ];
                            }
                        }
                    }
                }
            }
        }
        
        $return = [
            'taskTotal' => $studentNum,
            'makeTotal' => $tMakeNum,
            'data' => $data
        ];
        $this->success('试卷题块列表', $return);
    }


    //判卷信息
    public function makeExamnew()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $block_id = $this->request->post('block_id');
        $teacher_id = $this->request->post('teacher_id');
        $appraiseLevel = $this->request->post('appraiseLevel');
        $blockscore = $this->request->post('total');
        $type = $this->request->post('type');
        if (!$id || !$block_id || !$teacher_id || !in_array($type, [1, 2, 3, 4, 5])) $this->error('未知参数！');
        $distinguish = $this->request->param('distinguish/a');
        $paintList = $this->request->param('paintList/a');
        if (!is_array($distinguish) || !is_array($paintList)) $this->error('参数错误！');
        $blockInfo = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$blockInfo) $this->error('未找到相关题块信息！');
        $paperImage = db('exam_paper_images')->where(['student_id' => $id, 'exams_list_id' => $blockInfo['exams_list_id'], 'page' => 1])->find();
        if (!$paperImage) $this->error('未找到相关试卷信息!');
        $result = false;
        Db::startTrans();
        try {
           switch ($blockInfo['type']) {
               case 'alone':
                   if(!in_array($type, [1,4])) throw new Exception('未知参数！');
                   if($type == 4){
                       db('exam_teacher_make_log')->where(['exams_list_id' => $paperImage['exams_list_id'], 'student_id' => $paperImage['student_id'], 'block_id' => $block_id,'teacher_id'=>$teacher_id,'type'=>1])->delete();
                       $in = db('exam_teacher_make_log')->insertGetId([
                           'exams_id' => $paperImage['exams_id'],
                           'exams_list_id' => $paperImage['exams_list_id'],
                           'teacher_id' => $teacher_id,
                           'student_id' => $paperImage['student_id'],
                           'student_name' => $paperImage['student_name'],
                           'exam_number' => $paperImage['exam_number'],
                           'stu_number' => $paperImage['stu_number'],
                           'block_id' => $block_id,
                           'class_id' => $paperImage['class_id'],
                           'bscore' => $blockscore,
                           'appraiseLevel' => $appraiseLevel,
                           'distinguish' => json_encode($distinguish),
                           'paintList' => json_encode($paintList),
                           'type' => 4,
                           'createtime' => time()
                       ]);
                      
                   }else{
                       db('exam_teacher_make_log')->where(['exams_list_id' => $paperImage['exams_list_id'], 'student_id' => $paperImage['student_id'], 'block_id' => $block_id,'teacher_id'=>$teacher_id,'type'=>1])->delete();
                       $in = db('exam_teacher_make_log')->insertGetId([
                           'exams_id' => $paperImage['exams_id'],
                           'exams_list_id' => $paperImage['exams_list_id'],
                           'teacher_id' => $teacher_id,
                           'student_id' => $paperImage['student_id'],
                           'student_name' => $paperImage['student_name'],
                           'exam_number' => $paperImage['exam_number'],
                           'stu_number' => $paperImage['stu_number'],
                           'block_id' => $block_id,
                           'class_id' => $paperImage['class_id'],
                           'bscore' => $blockscore,
                           'appraiseLevel' => $appraiseLevel,
                           'distinguish' => json_encode($distinguish),
                           'paintList' => json_encode($paintList),
                           'type' => 1,
                           'createtime' => time()
                       ]);
                       
                   }
                   break;
               case 'dual':
                   if(!in_array($type, [2,3,5])) throw new Exception('未知参数！');
                   db('exam_teacher_make_log')->where(['exams_list_id' => $paperImage['exams_list_id'], 'student_id' => $paperImage['student_id'], 'block_id' => $block_id,'teacher_id'=>$teacher_id,'type'=>$type])->delete();
                   $in = db('exam_teacher_make_log')->insertGetId([
                       'exams_id' => $paperImage['exams_id'],
                       'exams_list_id' => $paperImage['exams_list_id'],
                       'teacher_id' => $teacher_id,
                       'student_id' => $paperImage['student_id'],
                       'student_name' => $paperImage['student_name'],
                       'exam_number' => $paperImage['exam_number'],
                       'stu_number' => $paperImage['stu_number'],
                       'block_id' => $block_id,
                       'class_id' => $paperImage['class_id'],
                       'bscore' => $blockscore,
                       'appraiseLevel' => $appraiseLevel,
                       'distinguish' => json_encode($distinguish),
                       'paintList' => json_encode($paintList),
                       'type' => $type,
                       'createtime' => time()
                   ]);
                   //终评判卷后计算两次判卷的差与阈值进行比较
                   if ($type == 3) {
                       $oneMakeScore = db('exam_teacher_make_log')->where(['exams_list_id' => $paperImage['exams_list_id'], 'student_id' => $paperImage['student_id'], 'block_id' => $block_id,'teacher_id'=>$teacher_id,'type'=>2])->value('bscore');
                       $poor = abs($oneMakeScore-$blockscore);
                       if ($poor > $blockInfo['threshold']) {
                           db('task')->insert([
                               'exams_id' => $blockInfo['exams_id'],
                               'exams_list_id' => $blockInfo['exams_list_id'],
                               'student_id' => $paperImage['student_id'],
                               'school_id' => $paperImage['school_id'],
                               'block_id' => $block_id,
                               'key' =>  'makeBlock'.$block_id,
                               'status' => 0,
                               'blockType' => $blockInfo['type'],
                               'num' =>  4,
                           ]);
                       }
                   }
                   
                   break;
           }
           if ($in) $result = true;
            if ($type == 1 || $type == 2 || $type == 3 || $type == 5) {
                db('task')->where(['exams_list_id' => $paperImage['exams_list_id'], 'block_id' => $block_id, 'student_id' => $paperImage['student_id'],'num'=>$type])->update(['status' => 2]);
            }

            //判断题块阅卷是否完成
            // $alreadynum = db('exam_paper_block')->where(['id' => $block_id])->value('alreadynum');
            $alreadynum = db('exam_paper_images')->where(['exams_list_id' => $paperImage['exams_list_id'],'page'=>1])->count();
            $studentnum = db('exam_list')->where(['id' => $paperImage['exams_list_id']])->value('studentnum');
            if ($alreadynum == $studentnum) {
                db('exam_paper_block')->where(['id' => $block_id])->update(['status' => 2]);
            }
            //判断科目阅卷是否完成
            //科目题块数量
            $blocknum = db('exam_paper_block')->where(['exams_list_id' => $paperImage['exams_list_id']])->count();
            //阅卷已完成的题块数
            $taskBlocknum = db('exam_paper_block')->where(['exams_list_id' => $paperImage['exams_list_id'], 'status' => 2])->count();
            if ($blocknum == $taskBlocknum) {
                db('exam_list')->where(['id' => $paperImage['exams_list_id']])->update(['status' => 3]);
            }
            //判断考试是否阅卷完成
            //科目总数
            $examListNum = db('exam_list')->where(['exams_id' => $paperImage['exams_id']])->count();
            //待统分科目总数
            $overTaskNum = db('exam_list')->where(['exams_id' => $paperImage['exams_id'], 'status' => 3])->count();
            if ($examListNum == $overTaskNum) {
                db('exams')->where(['id' => $paperImage['exams_id']])->update(['status' => 3]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加成功！');
        } else {
            $this->error('添加失败！');
        }
    }
}
